package com.maximporges.riatest.integration.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import com.maximporges.riatest.Integration;
import com.mysql.jdbc.Driver;

public class SqlIntegration extends Integration
{
   public static final String DRIVER_CLASS_PROPERTY_NAME = "driverClassName";
   public static final String JDBC_URL_PROPERTY_NAME = "jdbcurl";
   
   private Connection connection;

   @Override
   public String execute(String input) throws Exception
   {
      if (connection == null)
      {
         Driver driver = (Driver) Class.forName(getConfiguration().getConfiguration().getProperty(DRIVER_CLASS_PROPERTY_NAME)).getConstructor().newInstance();
         DriverManager.registerDriver(driver);
         connection = DriverManager.getConnection(getConfiguration().getConfiguration().getProperty(JDBC_URL_PROPERTY_NAME));
      }

      Statement statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery(input);
      StringBuffer result = new StringBuffer();
      while (resultSet.next())
      {
         result.append(resultSet.getString(1) + ",");
      }
      resultSet.close();
      statement.close();

      return result.substring(0, result.length() - 1);
   }
}
